import type { TableColumnProps, ProSaasTableExposeType } from '~/components/ProSaasTable/typings'
import type {
  SystemDeptOptionsType,
  SystemDeptPostDataItemType,
  SystemDeptStateType
} from './typings'
import { defineComponent, ref, reactive, onMounted } from 'vue'
import { useStore } from 'vuex'
import {
  ElDialog,
  ElFormItem,
  ElSelect,
  ElOption,
  ElButton,
  ElLink,
  ElIcon,
  ElMessage,
  ElMessageBox
} from 'element-plus'
import { View, Delete, Plus } from '@element-plus/icons-vue'
import { cloneDeep } from 'lodash'
import ProSaasTable from '~/components/ProSaasTable'
import useVuexGetters from '~/hooks/useVuexGetters'
import DeptPostOption from './deptPostOption'

export default defineComponent({
  name: 'DeptPost',
  props: ['visible', 'rowId'],
  emits: ['cancel'],
  setup(props: SystemDeptOptionsType, { emit }) {
    const store = useStore()
    // 初始值
    const proSaasTableRef = ref<ProSaasTableExposeType>()
    const deptPostListRef = ref()
    const searchFormValues = reactive<SystemDeptPostDataItemType>({})
    const state = reactive<SystemDeptStateType>({
      modalVisible: false,
      type: 'read',
      record: {}
    })

    const OrderState = useVuexGetters('order', ['tenantUserEnum'])

    onMounted(async () => {
      store.dispatch('order/GetDeptTreeSelectList') // 部门
      store.dispatch('order/GetTenantUserSelectList') // 人名 id转汉字
      getSelectByTenant()
    })

    // 岗位
    const getSelectByTenant = async () => {
      const res = await store.dispatch('systemDept/GetSelectByTenant') // 岗位
      if (res?.code === 200) {
        deptPostListRef.value = res.data
      }
    }

    // 新增、查看
    const handleChangeOptionsModal = (
      type: SystemDeptStateType['type'],
      record?: SystemDeptPostDataItemType
      // formEl?: FormInstance | undefined
    ) => {
      state.modalVisible = !state.modalVisible
      state.record = record || {}
      state.type = type
      if (!state.modalVisible) {
        proSaasTableRef.value!?.toSearch() // 更新主列表
      }
    }

    // 删除
    const handleOpenDeleteConfirm = (record?: SystemDeptPostDataItemType) => {
      if (!record && !proSaasTableRef.value!.selecteds?.length) {
        ElMessage({ type: 'warning', message: '请选择至少一条数据' })
        return
      }
      let params = ''
      if (record?.id) {
        params = record?.id
      } else {
        const element = cloneDeep(proSaasTableRef.value?.selecteds)
        const idsArr = element.map((item: { id: string }) => item.id) // 存待删的id们
        params = idsArr.join(',')
      }
      ElMessageBox.confirm('确定将选择数据删除?', {
        buttonSize: 'small',
        type: 'warning',
        closeOnClickModal: false, // 点遮罩层不关弹窗
        draggable: true // 可拖拽
      })
        .then(async () => {
          await store.dispatch('systemDept/PostDeptPostRemove', params).then((res) => {
            if (res?.code === 200) {
              proSaasTableRef.value!?.toSearch()
              ElMessage({ type: 'success', message: '操作成功' })
            } else {
              ElMessage({ type: 'error', message: res?.msg ?? '操作失败' })
            }
          })
        })
        .catch(() => {})
    }

    // 关闭弹框事件回调
    const handleCloseModal = () => {
      emit('cancel')
    }

    // 清空搜索
    const clearSearchTable = () => {
      if (searchFormValues.postId === '') {
        delete searchFormValues.postId // 岗位
      }
      proSaasTableRef.value!?.toSearch()
    }

    const columns: TableColumnProps<SystemDeptPostDataItemType>[] = [
      {
        label: '部门',
        prop: 'deptName',
        minWidth: 180,
        showOverflowTooltip: true,
        align: 'center'
      },
      {
        label: '岗位',
        prop: 'postName',
        minWidth: 180,
        showOverflowTooltip: true,
        align: 'center'
      },
      {
        label: '创建人',
        prop: 'createUser',
        minWidth: 180,
        enumValues: OrderState.tenantUserEnum,
        showOverflowTooltip: true,
        align: 'center'
      },
      {
        label: '创建时间',
        prop: 'createTime',
        minWidth: 180,
        showOverflowTooltip: true,
        align: 'center'
      },
      {
        label: '修改人',
        prop: 'updateUser',
        minWidth: 180,
        enumValues: OrderState.tenantUserEnum,
        showOverflowTooltip: true,
        align: 'center'
      },
      {
        label: '修改时间',
        prop: 'updateTime',
        minWidth: 180,
        showOverflowTooltip: true,
        align: 'center'
      },
      /* {
        label: '状态',
        prop: 'status',
        minWidth: 180,
        showOverflowTooltip: true,
        align: 'center'
      },
      {
        label: '是否已删除',
        prop: 'isDeleted',
        minWidth: 180,
        showOverflowTooltip: true,
        align: 'center',
        render: (_, value) => {
          if (value === 0) {
            return <>{'否'}</>
          } else if (value === 1) {
            return <>{'是'}</>
          } else {
            return <>{value}</>
          }
        }
      }, */
      {
        label: '操作',
        prop: 'options',
        fixed: 'right',
        minWidth: 180,
        width: 200,
        align: 'center',
        render: ({ row }) => {
          return (
            <>
              <ElLink type="primary" onClick={() => handleChangeOptionsModal('read', row)}>
                <ElIcon>
                  <View />
                </ElIcon>
                &nbsp;查看
              </ElLink>
              &nbsp;&nbsp;&nbsp;
              <ElLink type="primary" onClick={() => handleOpenDeleteConfirm(row)}>
                <ElIcon>
                  <Delete />
                </ElIcon>
                &nbsp;删除
              </ElLink>
            </>
          )
        }
      }
    ]

    return () => {
      return (
        <>
          <ElDialog
            width={'70%'}
            title="部门岗位"
            modelValue={props.visible}
            closeOnClickModal={false} // 点遮罩层不关弹窗
            draggable // 可拖拽
            beforeClose={handleCloseModal}
          >
            <ProSaasTable<SystemDeptPostDataItemType>
              ref={proSaasTableRef}
              columns={columns}
              hasIndex
              hasSelection
              searchFormProps={{
                model: searchFormValues
              }}
              searchParams={{ deptId: props.rowId }}
              searchformResponsiveCol={[
                <ElFormItem key="postId" prop="postId" label="岗位：">
                  <ElSelect
                    v-model={searchFormValues.postId}
                    placeholder="请选择 岗位"
                    clearable
                    onChange={() => {
                      proSaasTableRef.value!?.toSearch()
                    }}
                    onClear={clearSearchTable}
                  >
                    {deptPostListRef.value?.map((item: { id: string; postName: string }) => (
                      <ElOption key={item?.id} label={item?.postName} value={item?.id}></ElOption>
                    ))}
                  </ElSelect>
                </ElFormItem>
              ]}
              headerTitle={
                <>
                  <ElButton type="primary" onClick={() => handleChangeOptionsModal('add')}>
                    <ElIcon>
                      <Plus />
                    </ElIcon>
                    &nbsp; 新增
                  </ElButton>
                  <ElButton type="danger" plain onClick={() => handleOpenDeleteConfirm()}>
                    <ElIcon>
                      <Delete />
                    </ElIcon>
                    &nbsp; 删除
                  </ElButton>
                </>
              }
              dispatchType="systemDept/GetSystemDeptPostList"
            />
          </ElDialog>

          {/* 新增/编辑/查看 */}
          {state.modalVisible && (
            <DeptPostOption
              visible={state.modalVisible}
              type={state.type}
              record={state.record}
              rowId={props.rowId}
              onCancel={() => handleChangeOptionsModal('add')}
            />
          )}
        </>
      )
    }
  }
})
